package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"os/exec"
)

//go执行shell命令行
func execfun(pname string) []byte {
	defer fmt.Println("wait：等待执行...")
	defer fmt.Printf("job: completed!\n")
	fmt.Println("************************************")
	fmt.Println("开始执行:", pname)
	cmd := exec.Command("/bin/bash", "-c", pname)
	var out bytes.Buffer
	cmd.Stdout = &out
	var errout bytes.Buffer
	cmd.Stderr = &errout
	err := cmd.Run()
	if err != nil {
		fmt.Println("run：", pname, "field:", err)
		return []byte(errout.String())
	}
	return []byte(out.String())
}

//注册处理函数f1
func f1(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.Write([]byte("请使用POST方法！！"))
	} else {
		data, _ := ioutil.ReadAll(r.Body)
		w.Write(execfun(string(data)))
	}
}

func main() {
	http.HandleFunc("/cmd", f1)
	fmt.Println("程序现在开始！！")
	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		panic(err)
	}
}